﻿using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Documents;
using Serilog;
using ToolApp.EdgeRewards;

namespace ToolApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnFileNameChange_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtNameExp.Text) || string.IsNullOrWhiteSpace(TxtNewNameExp.Text))
            {
                return;
            }

            var files = GeFileInfos();
            if (files == null)
            {
                return;
            }
            RtbLogs.Document.Blocks.Clear();
            var paragraph = new Paragraph();
            var oldReg = new Regex(TxtNameExp.Text);
            foreach (var fileInfo in files)
            {
                var name = fileInfo.Name;
                if (string.IsNullOrWhiteSpace(fileInfo.Extension))
                {
                    name += ".flac";
                }
                var match = oldReg.Match(name);
                if (!match.Success)
                {
                    continue;
                }

                var newName = oldReg.Replace(name, TxtNewNameExp.Text);
                paragraph.Inlines.AddRange(new Inline[]
                    { new Run(name), new Bold(new Run(" -> ")), new Run(newName), new LineBreak() });
                //var fileName = fileInfo.Name[..fileInfo.Name.LastIndexOf('.')];
                //if (!fileName.Contains('-')) continue;
                //var nameList = fileName.Split('-').ToList();
                //for (var i = 0; i < nameList.Count; i++)
                //{
                //    nameList[i] = nameList[i].Trim();
                //}
                //var newName = " - " + nameList[0];
                //nameList.RemoveAt(0);
                //newName = string.Join("", nameList) + newName;
                fileInfo.MoveTo(fileInfo.DirectoryName + "\\" + newName);
            }
            RtbLogs.Document.Blocks.Add(paragraph);
        }

        private void BtnGetFiles_Click(object sender, RoutedEventArgs e)
        {
            var files = GeFileInfos();
            if (files == null)
            {
                return;
            }

            RtbLogs.Document.Blocks.Clear();
            var fileInfos = new List<FileInfo>();
            var paragraph = new Paragraph();
            foreach (var fileInfo in files.Where(f => !".lrc".Equals(f.Extension, StringComparison.OrdinalIgnoreCase))
                         .GroupBy(f => f.Name[..f.Name.LastIndexOf('.')]).Where(g => g.Count() > 1))
            {
                //paragraph.Inlines.Add(new Bold(new Run(fileInfo.Key)));
                foreach (var info in fileInfo)
                {
                    paragraph.Inlines.Add(new Run(info.FullName));
                    paragraph.Inlines.Add(new LineBreak());
                    if (!".flac".Equals(info.Extension, StringComparison.OrdinalIgnoreCase))
                    {
                        fileInfos.Add(info);
                    }
                }
            }
            RtbLogs.Document.Blocks.Add(paragraph);

            var paragraph1 = new Paragraph();
            foreach (var info in fileInfos)
            {
                paragraph1.Inlines.Add(new Run(info.FullName));
                paragraph1.Inlines.Add(new LineBreak());
                info.Delete();
            }
            RtbLogs.Document.Blocks.Add(paragraph1);
        }

        private FileInfo[]? GeFileInfos()
        {
            OpenFolderDialog folderDialog = new();
            if (folderDialog.ShowDialog() != true)
            {
                return null;
            }

            //var files = Directory.GetFiles(folderDialog.FolderName);
            var directoryInfo = new DirectoryInfo(folderDialog.FolderName);
            var files = directoryInfo.GetFiles();
            return files.Length == 0 ? null : files;
        }

        private async void BtnEdgeRewards_Click(object sender, RoutedEventArgs e)
        {
            var userList = new Dictionary<string, string>
            {
                { "xiong.leo@foxmail.com", "xiong369" },
                { "xiong.leo.he@qq.com", "xiong520" },
                { "18874757671@qq.com", "xiong520" },
            };
            var isMobile = false;
            var edgeRewards = new EdgeRewardsBase(isMobile);
            try
            {
                while (true)
                {
                    if (isMobile)
                    {
                        return;
                    }

                    foreach (var user in userList)
                    {
                        _ = new Login(edgeRewards, user.Key, user.Value);
                        if (!edgeRewards.IsMobile)
                        {
                            _ = new Activities(edgeRewards);
                        }

                        while (await new Searches(edgeRewards).BingSearches())
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(3));
                        }
                    }

                    edgeRewards.Quit();
                    edgeRewards.WebDriver = null;
                    isMobile = true;
                }
            }
            catch (Exception ex)
            {
                edgeRewards.Quit();
                Log.Error(ex, ex.Message);
            }
        }
    }
}